from django import http

from django.contrib.auth import logout,login
from django.contrib.auth.hashers import check_password

from apps.users.models import User
from django.http import JsonResponse
from aijia_house.utils.login import LoginRequiredJSONMixin
from libs.check_id_card import checkIdcard
from libs.response_code import RET

from django.views import View
import json
import re


class LoginView(View):

    def post(self, request):
        '''实现登录接口'''
        # 1.接收参数
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get('mobile')
        password = data_dict.get('password')

        # 2.校验(整体 + 单个)
        if not all([mobile, password]):
            return JsonResponse({'errno': RET.PARAMERR,'errmsg': "参数错误"})

        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            return JsonResponse({'errno': RET.DBERR, 'errmsg': "查询错误"})
        # 判断是否为空,如果为空,返回
        if user is None:
            return JsonResponse({'errno': RET.LOGINERR,'errmsg': "登录失败"})
        if not check_password(password,user.password):
            return JsonResponse({'errno': RET.LOGINERR, 'errmsg': "登录失败"})

        # 4.状态保持
        login(request, user)
        # 生成响应对象
        return JsonResponse({'errno': RET.OK,'errmsg': "登录成功"})

class SessionView(LoginRequiredJSONMixin, View):
    '''获取登录状态'''
    def get(self,request):
        user = request.user
        data = {
            'user_id': user.pk,
            'name': user.username
        }
        return JsonResponse({"errno": RET.OK, "errmsg": "OK", "data": data})


class UserInfoView(LoginRequiredJSONMixin,View):
    '''用户中心'''
    def get(self,request):
        '''用户中心显示'''
        user = request.user
        data = {
            "name": user.username,
            "avatar_url": "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1594632833&di=cb9aa3eae6a0101c421f2a8f5d3b5b81&src=http://bbsfiles.vivo.com.cn/vivobbs/attachment/forum/201610/10/223520gj6otfv9t51t9oi9.jpg",
            "mobile": user.mobile
        }
        return JsonResponse({ "errno": RET.OK, "errmsg": "OK", "data": data })

    def post(self,request):
        '''修改用户名'''
        data_dict = json.loads(request.body.decode())
        name = data_dict.get('name')
        if not name:
            return JsonResponse({"errno": RET.NODATA, "errmsg": "无数据"})
        user = request.user
        user.username = name
        try:
            user.save()
        except Exception as e:
            return JsonResponse({"errno": RET.DATAERR, "errmsg": "失败"})
        return JsonResponse({ "errno": RET.OK, "errmsg": "OK"})

class LogoutView(LoginRequiredJSONMixin,View):
    '''退出登录'''
    def delete(self,request):
        logout(request)
        return JsonResponse({'errno': RET.OK,'errmsg': "退出成功"})


class RegisterView(View):

    def post(self, request):
        '''接收参数, 保存到数据库'''
         # 1.接收参数：请求体中的JSON数据 request.body
        json_bytes = request.body # 从请求体中获取原始的JSON数据，bytes类型的
        json_str = json_bytes.decode() # 将bytes类型的JSON数据，转成JSON字符串
        json_dict = json.loads(json_str) # 将JSON字符串，转成python的标准字典
        # json_dict = json.loads(request.body.decode())

        # 提取参数
        mobile = json_dict.get('mobile')
        phonecode = json_dict.get('phonecode')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')

        # 2.校验(整体参数是否为空)
        if not all([password, password2, mobile, phonecode]):
            return http.JsonResponse({'errno':4002, 'errmsg':'缺少必传参数!'})

        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'errno': 4004, 'errmsg': 'password格式有误!'})

        # 5.password2 和 password
        if password != password2:
            return http.JsonResponse({'errno': 4103, 'errmsg': '两次输入不对!'})
        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': 4004, 'errmsg': 'mobile格式有误!'})

        # redis_conn = get_redis_connection('verify_code')
        # sms_code_server = redis_conn.get('sms_%s' % mobile)  # sms_code_server是bytes
        # # 判断短信验证码是否过期
        # if not sms_code_server:
        #     return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # # 对比用户输入的和服务端存储的短信验证码是否一致
        # if phonecode != sms_code_server.decode():
        #     return http.JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})
        #
        # # 8.注册的核心逻辑-保存到数据库 (username password mobile)


        # 5.password2 和 password
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})

        # 8.注册的核心逻辑-保存到数据库 (username password mobile)
        try:
            user = User.objects.create_user(

                                             password=password,
                                             mobile=mobile,

                                             username= mobile
            )
        except Exception as e:
            return http.JsonResponse({'errno': 4501, 'errmsg': '注册失败!'})
        # 实现状态保持
        # login(request, user)

        # 13.拼接json返回

        return http.JsonResponse({'errno': 0, 'errmsg': '注册成功!'})

class IdcardView(LoginRequiredJSONMixin,View):
    def post(self,request):
        data_dict = json.loads(request.body.decode())
        real_name = data_dict.get("real_name")
        id_card = data_dict.get("id_card")
        if not all([real_name,id_card]):
            return http.JsonResponse({'errno': 4003, 'errmsg': "保存数据失败"})
        if checkIdcard(id_card) == '验证通过!':

            try:
                request.user.real_name = real_name
                request.user.id_card = id_card
                request.user.save()
            except Exception as e:
                return http.JsonResponse({'errno': 4003, 'errmsg': "保存数据失败"})
            return http.JsonResponse({'errno': 0, 'errmsg': "保存成功"})
        else:
            return http.JsonResponse({'errno': 4003, 'errmsg': "保存数据失败"})
    def get(self,request):
        user = request.user
        data = {
            "real_name":user.real_name,
            "id_card":user.id_card

        }
        return http.JsonResponse({'errno': 0, 'errmsg': "success", 'data': data})

# 房屋发布列表
class UserHouse(LoginRequiredJSONMixin, View):
    '''
    获取用户房屋列表
    查询房屋数据但会数据
    '''
    def get(self, request):
        user = request.user
        try:
            houses = user.house_set.all()
        except Exception as e:
            return http.JsonResponse({'errno': 4001, 'errmsg': "查询数据失败"})

        houses_dict = []
        for house in houses:
            houses_dict.append({
                "house_id": house.id,
                "title": house.title,
                "price": house.price,
                "area_name": house.area.name,
                "img_url": house.index_image.url,
                "room_count": house.room_count,
                "order_count": house.order_count,
                "address": house.address,
                "user_avatar": house.user.avatar.url,
                "ctime": house.create_time.strftime("%Y-%m-%d")
            })

        return http.JsonResponse({'errno': 0, 'errmsg': "OK,查询成功", 'data': houses_dict})

